const db = uniCloud.database();
const dbCmd = db.command;

export default {
	
	
	createUser(userInfo, openid) {
		return new Promise(async (resolve, reject) => {
			resolve(
			await db.collection('uni-id-users').where({wx_openid:{"mp-weixin":openid}}).update({
				nickname: userInfo.nickName,
				avatar: userInfo.avatarUrl,
				correct_ti:[],
				error_ti:[],
				star_ti:[]
			}))
			
		}) 

	},
	getUser(openid) 
	{
		return new Promise(async (resolve,reject)=>{
			resolve(await db.collection('uni-id-users').where(dbCmd.and([{
						wx_openid: {
							"mp-weixin":openid
						}
					}, {
						nickname: dbCmd.exists(true)
					}])).get({getOne:true}))
		})
	},
	getti(id)
	{
		return new Promise(async (resolve,reject)=>{
			resolve(await db.collection('tiku').where({_id:id}).get({getOne:true}))
		})
	},
	getUserInfo(openid) {
		return new Promise((resolve, reject) => {

			uni.getUserProfile({
				desc: 'Wexin', // 这个参数是必须的   
				success: res => {
					resolve(res.userInfo)
				},
				fail: err => {
					reject(err);
					uni.showToast({
						title: "您取消了授权,登录失败",
						icon: "none"
					});
				}
			})
		})

	},
	getWeixinCode() {
		return new Promise((resolve, reject) => {

			uni.login({
				provider: 'weixin',
				success(res) {
					
					resolve(res.code)
				},
				fail(err) {
					reject(new Error('微信登录失败'))
				}
			})

		})
	},
	async checkLogined() {
		let openid = uni.getStorageSync('openid');
		
		let loginTime = uni.getStorageSync('loginTime');
		// console.log(new Date().getTime()-loginTime);
		if(!openid)
			return '未登录';
		let res=await db.collection('uni-id-users').where(dbCmd.and([{
			wx_openid: {
				"mp-weixin": openid
			}
		}, {
			nickname: dbCmd.exists(true)
		}])).get({
			getOne: true 
		});
		  
		let userexist='data' in res.result;
		console.log(userexist);
		if (!userexist) {
			return "未注册";
		} else if((new Date()).getTime()-loginTime > 24 * 3600 * 1000) {
			return "已过期";
		}   
		else   
		{
			return "已登录";
		}
	
	},
	async upTi(tis,state)
	{
		uniCloud.callFunction({
			name:'upTi',
			data:{
				tis:tis,
				state:state,
				openid:uni.getStorageSync('openid')
			},
			success: (e) => {
				return e
			},
			fail:e=>{return e}
		})
	},
	async login() {
		let userinfo = await this.getUserInfo();
		uni.showLoading({ 
			title: '登录中',
			mask: false
		});  
		  
		uni.setStorageSync('avatar', userinfo.avatarUrl);
		
		uni.setStorageSync('name', userinfo.nickName);
		uni.setStorageSync('loginTime', (new Date()).getTime());
		
		return new Promise((resolve, reject) => {
		
			 
			this.getWeixinCode().then((code) => {
				console.log(code)
				uniCloud.callFunction({
					name:'loginWeixin',
					data:{
						code
					},
					fail: (err) => {
						console.log(err)
					},
					success: (cts) => {
							console.log("openid获取成功！")
							console.log(cts)
						
							// 换取成功后 暂存这些数据 留作后续操作  
							let openid=cts.result.openid     //openid 用户唯一标识  
							console.log(openid)
							// this.unionid=cts.data.unionid     //unionid 开放平台唯一标识  
							let session_key=cts.result.sessionkey     //session_key  会话密钥  
							  
							db.collection('uni-id-users').where(dbCmd.and([{
								wx_openid: {
									"mp-weixin": openid 
								}
							}, {
								nickname: dbCmd.exists(true)
							}])).get({ 
								getOne: true
							}).then(async (res1) => { 
								   
								if (res1.result.data) {
									console.log('用户存在')
									// let pages = getCurrentPages();
									// let curPage = pages[pages.length - 1];
									// console.log(curPage) 
									uni.setStorageSync('openid', openid); 
									 
									let check=await this.checkLogined()
									console.log(check)
									uni.setStorageSync('loginStatus',check) 
									
									// curPage.onLoad();
									uni.hideLoading() 
									uni.reLaunch({
										url:'/pages/index/index'
									})
								} else {  
									console.log("用户注册")  
									await this.createUser(userinfo, openid); 
									// let pages = getCurrentPages();
									// let curPage = pages[pages.length - 1]; 
									   
									uni.setStorageSync('openid', openid); 
									let check=await this.checkLogined()
									uni.setStorageSync('loginStatus',check) 
									// curPage.onLoad();
									console.log(check)
									uni.hideLoading() 
									uni.reLaunch({
										url:'/pages/index/index',
										fail: (e) => {
											console.log(e)
										}
									})
								}  
						
							} )
						
					}
				})
			
				
			})

		})
	}
		
}

